<script setup>
import { ref, computed } from "vue";
import { Delete, View, Download } from "@element-plus/icons-vue";

const props = defineProps(["data", "noDataDes", "type"]);
const eventProps = defineEmits(["delImage", "downloadImage", "loadError"]);

const imageRef = ref();
const previewIndex = ref(0);
const existsData = computed(() => props?.data?.length);
const previewImageList = computed(() => props.data.map((item) => item.url));

const openPreview = (index) => {
  const targetImage = imageRef?.value?.[index];
  if (!targetImage) return false;
  previewIndex.value = index;
  targetImage.$el.children[0].click();
};
const delImage = (item, index) => {
  eventProps("delImage", { info: item, index });
};

const downloadImage = (item) => {
  eventProps("downloadImage", item);
};

const loadError = (item) => {
  eventProps(["loadError", item]);
};
</script>

<template>
  <el-space
    :class="{ previewUplaodSpace: true, notData: !existsData }"
    :wrap="true"
    alignment="flex-start"
  >
    <template v-if="existsData">
      <section
        class="image"
        v-for="(item, index) in props.data || []"
        :key="item.name"
      >
        <el-image
          ref="imageRef"
          :initial-index="previewIndex"
          :preview-src-list="previewImageList"
          :src="item.url"
          @error="loadError"
        />
        <span class="preview">
          <el-icon @click="openPreview.call(this, index)" class="icon viewIcon">
            <View />
          </el-icon>

          <el-icon @click="downloadImage(item)" class="icon delIcon">
            <Download />
          </el-icon>

          <el-icon
            @click="delImage.call(this, item, index)"
            class="icon delIcon"
          >
            <Delete />
          </el-icon>
        </span>
      </section>
    </template>
    <el-empty
      v-else
      class="emptyStatus"
      :description="props.noDataDes || '暂无图片资源'"
    />
  </el-space>
</template>

<style lang="less" scoped>
@import url("./index.less");
</style>
